package com.pt.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pt.common.ApiResponse;
import com.pt.entity.Torrent;
import com.pt.entity.User;
import com.pt.service.TorrentService;
import com.pt.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.List;
import java.util.HashMap;

import com.pt.dto.response.InvitationResponse;
import com.pt.entity.Invitation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
@Api(tags = "管理员接口")
public class AdminController {
    
    private final UserService userService;
    private final TorrentService torrentService;
    private static final Logger log = LoggerFactory.getLogger(AdminController.class);
    
    @GetMapping("/users")
    @ApiOperation("获取用户列表")
    public ApiResponse<Page<User>> getUsers(
            @ApiParam("关键词") @RequestParam(required = false) String keyword,
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") int size) {
        
        Page<User> users = userService.listUsersByKeyword(keyword, page, size);
        return ApiResponse.success(users);
    }
    
    @PutMapping("/users/{userId}/class")
    @ApiOperation("修改用户等级")
    public ApiResponse<String> updateUserClass(
            @ApiParam("用户ID") @PathVariable Long userId,
            @ApiParam("新等级") @RequestParam Integer userClass) {
        
        userService.updateUserClass(userId, userClass);
        return ApiResponse.success("用户等级修改成功");
    }
    
    @PutMapping("/users/{userId}/status")
    @ApiOperation("修改用户状态")
    public ApiResponse<String> updateUserStatus(
            @ApiParam("用户ID") @PathVariable Long userId,
            @ApiParam("新状态") @RequestParam Integer status) {
        
        userService.updateUserStatus(userId, status);
        return ApiResponse.success("用户状态修改成功");
    }
    
    @GetMapping("/torrents/pending")
    @ApiOperation("获取待审核种子列表")
    public ApiResponse<Page<Torrent>> getPendingTorrents(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") int size) {
        
        System.out.println("=== 获取待审核种子列表 ===");
        System.out.println("页码: " + page + ", 每页数量: " + size);
        
        Page<Torrent> torrents = torrentService.getPendingTorrents(page, size);
        System.out.println("查询到待审核种子数量: " + torrents.getTotal());
        System.out.println("当前页种子数量: " + torrents.getRecords().size());
        
        return ApiResponse.success(torrents);
    }
    
    @PutMapping("/torrents/{torrentId}/approve")
    @ApiOperation("审核通过种子")
    public ApiResponse<String> approveTorrent(@ApiParam("种子ID") @PathVariable Long torrentId) {
        System.out.println("=== 审核通过种子 ===");
        System.out.println("种子ID: " + torrentId);
        
        torrentService.approveTorrent(torrentId);
        System.out.println("种子审核通过成功");
        
        return ApiResponse.success("种子审核通过");
    }
    
    @PutMapping("/torrents/{torrentId}/reject")
    @ApiOperation("拒绝种子")
    public ApiResponse<String> rejectTorrent(
            @ApiParam("种子ID") @PathVariable Long torrentId,
            @ApiParam("拒绝原因") @RequestBody Map<String, String> request) {
        
        System.out.println("=== 拒绝种子 ===");
        System.out.println("种子ID: " + torrentId);
        
        String reason = request.get("reason");
        if (reason == null || reason.trim().isEmpty()) {
            return ApiResponse.error("拒绝原因不能为空");
        }
        
        System.out.println("拒绝原因: " + reason);
        
        torrentService.rejectTorrent(torrentId, reason);
        System.out.println("种子拒绝成功");
        
        return ApiResponse.success("种子已拒绝");
    }
    
    @GetMapping("/stats/overview")
    @ApiOperation("获取站点概览统计")
    public ApiResponse<Map<String, Object>> getSiteOverview() {
        Map<String, Object> overview = userService.getSiteOverview();
        return ApiResponse.success(overview);
    }
    
    @GetMapping("/stats/traffic")
    @ApiOperation("获取流量统计")
    public ApiResponse<Map<String, Object>> getTrafficStats(
            @ApiParam("统计天数") @RequestParam(defaultValue = "30") int days,
            @ApiParam("开始日期") @RequestParam(required = false) String startDate,
            @ApiParam("结束日期") @RequestParam(required = false) String endDate) {
        
        Map<String, Object> stats = userService.getDailyTrafficStats(days, startDate, endDate);
        return ApiResponse.success(stats);
    }
    
    @GetMapping("/stats/active-users")
    @ApiOperation("获取活跃用户统计")
    public ApiResponse<Map<String, Object>> getActiveUserStats(
            @ApiParam("统计天数") @RequestParam(defaultValue = "30") int days,
            @ApiParam("开始日期") @RequestParam(required = false) String startDate,
            @ApiParam("结束日期") @RequestParam(required = false) String endDate) {
        
        Map<String, Object> stats = userService.getActiveUserStats(days, startDate, endDate);
        return ApiResponse.success(stats);
    }
    
    @GetMapping("/invitations")
    @ApiOperation("获取邀请码列表")
    public ApiResponse<Page<InvitationResponse>> getInvitations(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") int size) {
        
        Page<Invitation> invitationPage = userService.getInvitationList(page, size);
        
        // 转换为响应DTO
        Page<InvitationResponse> responsePage = new Page<>(page, size);
        responsePage.setTotal(invitationPage.getTotal());
        responsePage.setPages(invitationPage.getPages());
        responsePage.setCurrent(invitationPage.getCurrent());
        responsePage.setSize(invitationPage.getSize());
        
        java.util.List<InvitationResponse> responseList = invitationPage.getRecords().stream()
                .map(invitation -> {
                    InvitationResponse response = InvitationResponse.fromEntity(invitation);
                    // 如果邀请码已被使用，查询使用者用户名
                    if (invitation.getUsedBy() != null) {
                        User user = userService.getUserById(invitation.getUsedBy());
                        if (user != null) {
                            response.setUsedByUsername(user.getUsername());
                        }
                    }
                    return response;
                })
                .collect(java.util.stream.Collectors.toList());
        responsePage.setRecords(responseList);
        
        return ApiResponse.success(responsePage);
    }
    
    @PostMapping("/invitations/create")
    @ApiOperation("创建邀请码")
    public ApiResponse<InvitationResponse> createInvitationCode() {
        User currentUser = userService.getCurrentUser();
        Invitation invitation = userService.createInvitationCode(currentUser.getId());
        InvitationResponse response = InvitationResponse.fromEntity(invitation);
        return ApiResponse.success(response);
    }
    
    @PostMapping("/invitations/batch")
    @ApiOperation("批量创建邀请码")
    public ApiResponse<java.util.List<InvitationResponse>> createBatchInvitationCodes(
            @ApiParam("数量") @RequestParam(defaultValue = "5") Integer count) {
        
        if (count > 50) {
            return ApiResponse.error("一次最多只能创建50个邀请码");
        }
        
        User currentUser = userService.getCurrentUser();
        java.util.List<InvitationResponse> responses = new java.util.ArrayList<>();
        
        for (int i = 0; i < count; i++) {
            Invitation invitation = userService.createInvitationCode(currentUser.getId());
            InvitationResponse response = InvitationResponse.fromEntity(invitation);
            responses.add(response);
        }
        
        return ApiResponse.success(responses);
    }
    
    @DeleteMapping("/invitations/{invitationId}")
    @ApiOperation("删除邀请码")
    public ApiResponse<String> deleteInvitationCode(@ApiParam("邀请码ID") @PathVariable Long invitationId) {
        try {
            userService.deleteInvitationCode(invitationId);
            return ApiResponse.success("邀请码删除成功");
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PostMapping("/notifications/email")
    @ApiOperation("发送邮件通知")
    public ApiResponse<String> sendEmailNotification(
            @ApiParam("邮件主题") @RequestParam String subject,
            @ApiParam("邮件内容") @RequestParam String content,
            @ApiParam("目标用户ID，为空则发送给所有用户") @RequestParam(required = false) Long targetUserId) {
        
        try {
            if (targetUserId != null) {
                // 发送给指定用户
                User targetUser = userService.getById(targetUserId);
                if (targetUser == null) {
                    return ApiResponse.error("目标用户不存在");
                }
                // 这里需要实现邮件服务
                // emailService.sendNotificationEmail(targetUser.getEmail(), subject, content);
            } else {
                // 发送给所有用户
                // 这里需要实现批量邮件发送
                // emailService.sendBulkNotificationEmail(subject, content);
            }
            return ApiResponse.success("邮件通知发送成功");
        } catch (Exception e) {
            return ApiResponse.error("发送邮件通知失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/notifications/system")
    @ApiOperation("发送系统通知")
    public ApiResponse<String> sendSystemNotification(
            @ApiParam("通知标题") @RequestParam String title,
            @ApiParam("通知内容") @RequestParam String content,
            @ApiParam("目标用户ID，为空则发送给所有用户") @RequestParam(required = false) Long targetUserId) {
        
        try {
            if (targetUserId != null) {
                // 发送给指定用户
                User targetUser = userService.getById(targetUserId);
                if (targetUser == null) {
                    return ApiResponse.error("目标用户不存在");
                }
                // 这里需要实现系统通知服务
                // notificationService.sendSystemNotification(targetUserId, title, content);
            } else {
                // 发送给所有用户
                // notificationService.sendBulkSystemNotification(title, content);
            }
            return ApiResponse.success("系统通知发送成功");
        } catch (Exception e) {
            return ApiResponse.error("发送系统通知失败: " + e.getMessage());
        }
    }

    @PostMapping("/notifications/broadcast")
    @ApiOperation("发送全站通知")
    public ApiResponse<Void> sendBroadcastNotification(@RequestBody Map<String, String> request) {
        try {
            String title = request.get("title");
            String content = request.get("content");
            String type = request.get("type"); // email 或 system
            
            if (title == null || title.trim().isEmpty()) {
                return ApiResponse.error("通知标题不能为空");
            }
            
            if (content == null || content.trim().isEmpty()) {
                return ApiResponse.error("通知内容不能为空");
            }
            
            // 获取所有正常状态的用户
            List<User> users = userService.lambdaQuery()
                    .eq(User::getStatus, 1)
                    .list();
            
            if ("email".equals(type)) {
                // 发送邮件通知
                for (User user : users) {
                    // 这里应该调用邮件服务发送邮件
                    log.info("向用户 {} 发送邮件通知: {}", user.getEmail(), title);
                }
            } else {
                // 发送系统通知
                for (User user : users) {
                    // 这里应该调用系统通知服务
                    log.info("向用户 {} 发送系统通知: {}", user.getUsername(), title);
                }
            }
            
            return ApiResponse.success(null);
        } catch (Exception e) {
            log.error("发送全站通知失败", e);
            return ApiResponse.error("发送失败: " + e.getMessage());
        }
    }

    @GetMapping("/user-assessment/check/{userId}")
    @ApiOperation("检查单个用户考核状态")
    public ApiResponse<Map<String, Object>> checkUserAssessment(@PathVariable Long userId) {
        try {
            Map<String, Object> result = userService.checkUserAssessment(userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("检查用户考核状态失败", e);
            return ApiResponse.error("检查失败: " + e.getMessage());
        }
    }

    @PostMapping("/user-assessment/batch-check")
    @ApiOperation("批量检查所有用户考核状态")
    public ApiResponse<List<Map<String, Object>>> batchCheckAssessments() {
        try {
            List<Map<String, Object>> results = userService.batchCheckAssessments();
            return ApiResponse.success(results);
        } catch (Exception e) {
            log.error("批量检查用户考核状态失败", e);
            return ApiResponse.error("批量检查失败: " + e.getMessage());
        }
    }

    @PostMapping("/user-assessment/set/{userId}")
    @ApiOperation("设置用户考核期")
    public ApiResponse<Void> setUserAssessment(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "30") Integer assessmentDays) {
        try {
            userService.setUserAssessment(userId, assessmentDays);
            return ApiResponse.success(null);
        } catch (Exception e) {
            log.error("设置用户考核期失败", e);
            return ApiResponse.error("设置失败: " + e.getMessage());
        }
    }

    @PostMapping("/user-assessment/cancel/{userId}")
    @ApiOperation("取消用户考核")
    public ApiResponse<Void> cancelUserAssessment(@PathVariable Long userId) {
        try {
            userService.cancelUserAssessment(userId);
            return ApiResponse.success(null);
        } catch (Exception e) {
            log.error("取消用户考核失败", e);
            return ApiResponse.error("取消失败: " + e.getMessage());
        }
    }

    @GetMapping("/user-assessment/list")
    @ApiOperation("获取考核期用户列表")
    public ApiResponse<List<User>> getAssessmentUsers() {
        try {
            List<User> users = userService.lambdaQuery()
                    .eq(User::getStatus, 3) // 考核中状态
                    .isNotNull(User::getAssessmentDeadline)
                    .orderByAsc(User::getAssessmentDeadline)
                    .list();
            return ApiResponse.success(users);
        } catch (Exception e) {
            log.error("获取考核期用户列表失败", e);
            return ApiResponse.error("获取失败: " + e.getMessage());
        }
    }

    @PostMapping("/promotion/auto-manage")
    @ApiOperation("执行自动促销管理")
    public ApiResponse<Void> autoPromotionManagement() {
        try {
            // 通过反射调用TorrentServiceImpl的autoPromotionManagement方法
            if (torrentService instanceof com.pt.service.impl.TorrentServiceImpl) {
                com.pt.service.impl.TorrentServiceImpl impl = 
                    (com.pt.service.impl.TorrentServiceImpl) torrentService;
                impl.autoPromotionManagement();
            }
            return ApiResponse.success(null);
        } catch (Exception e) {
            log.error("自动促销管理失败", e);
            return ApiResponse.error("执行失败: " + e.getMessage());
        }
    }

    @GetMapping("/promotion/stats")
    @ApiOperation("获取促销统计信息")
    public ApiResponse<Map<String, Object>> getPromotionStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            if (torrentService instanceof com.pt.service.impl.TorrentServiceImpl) {
                com.pt.service.impl.TorrentServiceImpl impl = 
                    (com.pt.service.impl.TorrentServiceImpl) torrentService;
                stats = impl.getPromotionStats();
            }
            return ApiResponse.success(stats);
        } catch (Exception e) {
            log.error("获取促销统计失败", e);
            return ApiResponse.error("获取失败: " + e.getMessage());
        }
    }

    @PutMapping("/users/{userId}/admin")
    @ApiOperation("修改用户管理员状态")
    public ApiResponse<String> updateUserAdminStatus(
            @ApiParam("用户ID") @PathVariable Long userId,
            @RequestBody Map<String, Boolean> request) {
        
        Boolean isAdmin = request.get("isAdmin");
        if (isAdmin == null) {
            return ApiResponse.error("参数错误");
        }
        
        userService.updateUserAdminStatus(userId, isAdmin);
        return ApiResponse.success("管理员状态修改成功");
    }
} 